package com.gdth.bank.activity;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.text.format.DateUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;

import com.gdth.bank.BankApplication;
import com.gdth.bank.R;
import com.gdth.bank.adapter.DzCpKhListViewAdapter.OnCjjlDetailClickListener;
import com.gdth.bank.adapter.DzCpKhPosListViewAdapter;
import com.gdth.bank.bean.DzCpItem;
import com.gdth.bank.presenter.DzCpKhXxPosPresenter;
import com.gdth.bank.view.DzCpKhXxPosView;
import com.gdth.bank.widget.DialogConfigSpinner;
import com.gdth.core.annotation.view.ViewInject;
import com.gdth.core.widget.BaseActivity;
import com.gdth.database.bean.DzCpkhXxDjPos;
import com.gdth.database.bean.TAppYh;
import com.gdth.widget.dialog.BaseToast;
import com.gdth.widget.pulltorefresh.library.PullToRefreshBase;
import com.gdth.widget.pulltorefresh.library.PullToRefreshListView;
import com.gdth.widget.pulltorefresh.library.PullToRefreshBase.Mode;
import com.gdth.widget.pulltorefresh.library.PullToRefreshBase.OnLastItemVisibleListener;
import com.gdth.widget.pulltorefresh.library.PullToRefreshBase.OnRefreshListener;

public class DzCpPosGeRenXxActivity extends BaseActivity implements DzCpKhXxPosView{
	@ViewInject(id=R.id.header_label_title) TextView txt_header_title;
	@ViewInject(id=R.id.header_btn_left, click="finishClick") TextView txt_header_left;
	@ViewInject(id=R.id.header_btn_right, click="addClick") TextView txt_header_right;
    @ViewInject(id=R.id.dzcpkhxx_query, click="queryClick") TextView txt_query;
    @ViewInject(id=R.id.dzcp_editTextNote) EditText edit_query;
	@ViewInject(id=R.id.listView) PullToRefreshListView listView;
	ListView mListView;
	List<DzCpItem> listData;
	DzCpKhPosListViewAdapter mAdapter;
	ProgressDialog mProgressDialog;
	DzCpKhXxPosPresenter mDzCpKhXxPosPresenter;
	private String offset="1";//上拉
    private String upset= "1";//下拉
    List<DzCpkhXxDjPos>  dzcpkhxxposList;
    String app_uuid;
    String lx="";
    String strs="";
    List<String> list= new ArrayList<String>();
    int positions;
    DialogConfigSpinner config;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_dzcpkhxxdjl_list);
        initView();
	    init();
		
	}
	private void initView() {
		txt_header_title.setText(R.string.param197);
		txt_header_right.setVisibility(View.VISIBLE);
		txt_header_right.setBackgroundResource(R.drawable.more_srarch_32);
		 mProgressDialog = new ProgressDialog(this);
			
	        mListView = listView.getRefreshableView();
	        mListView.setDivider(new ColorDrawable(R.color.line_color));  
	        mListView.setDividerHeight(1);
	        listView.setOnRefreshListener(new OnRefreshListener<ListView>() {
				@Override
				public void onRefresh(PullToRefreshBase<ListView> refreshView) {
					String label = DateUtils.formatDateTime(getApplicationContext(), System.currentTimeMillis(),
							DateUtils.FORMAT_SHOW_TIME | DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_ABBREV_ALL);
					
					refreshView.getLoadingLayoutProxy().setLastUpdatedLabel(label);
					String val = edit_query.getText().toString();
					if(refreshView.isHeaderShown()){
						int listDataSize=listData.size();
						TAppYh user = BankApplication.mInstance.getCurrentUser();
						  String dqr = user.getZh();
						String time;
						if(listDataSize>0){
							time =listData.get(0).getDate();
						}else{
							 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	   						 time = sdf.format(new Date());
						}
						JSONObject content  =new JSONObject();
                        try {
                        	content.put("time", time);
                        	content.put("dqr", dqr);
                        	content.put("val", val);
                        	content.put("strs", strs);
                		} catch (JSONException e) {
                			// TODO Auto-generated catch block
                			e.printStackTrace();
                		}
                        mDzCpKhXxPosPresenter.getUpDzcpPosGeRenJl(content.toString());
						Toast.makeText(getApplicationContext(), "下拉刷新",Toast.LENGTH_SHORT).show();
						
                      }else {
                    	  int listDataSize=listData.size();
  						TAppYh user = BankApplication.mInstance.getCurrentUser();
  						  String dqr = user.getZh();
  						String time;
  						if(listDataSize>0){
  							time =listData.get(listDataSize-1).getDate();
  						}else{
  							 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
  	   						 time = sdf.format(new Date());
  						}
  						JSONObject content  =new JSONObject();
                          try {
                          	content.put("time", time);
                          	content.put("dqr", dqr);
                          	content.put("val", val);
                          	content.put("strs", strs);
                  		} catch (JSONException e) {
                  			// TODO Auto-generated catch block
                  			e.printStackTrace();
                  		}
                          mDzCpKhXxPosPresenter.getOffDzcpPosGeRenJl(content.toString());
  						Toast.makeText(getApplicationContext(), "上拉刷新",Toast.LENGTH_SHORT).show();

							                    //上拉加载更多 业务代码
							                    //上拉加载更多 业务代码
							                }
					
				}
			});

	        listView.setOnLastItemVisibleListener(new OnLastItemVisibleListener() {
				@Override
				public void onLastItemVisible() {
					
				}
			});
	        
	        listData = new ArrayList<DzCpItem>();
	        
	        
	        mAdapter = new DzCpKhPosListViewAdapter(this, listData);
//	        mAdapter.setOnCjjlDetailClickListener(new OnDetailClickListener());

	        listView.setAdapter(mAdapter);
	        
	        listView.setOnItemClickListener(new OnItemClickListener(){

				@Override
				public void onItemClick(AdapterView<?> parent, View view,
						int position, long id) {
					// TODO Auto-generated method stub
					 DzCpItem item=listData.get(position-1);
					   String appuuid=	item.getKey();
					   String zt=item.getZt();
					   if(zt.equals("0")){
						   Intent intent=new Intent();
						   intent.setClass(DzCpPosGeRenXxActivity.this, DzCpKhXxPosGeRenXxMxXgActivity.class);
						   intent.putExtra("appuuid", appuuid);
						   startActivity(intent);
					   }else{
						   Intent intent=new Intent();
						   intent.setClass(DzCpPosGeRenXxActivity.this, DzCpKhXxPosGeRenXxMxActivity.class);
						   intent.putExtra("appuuid", appuuid);
						   startActivity(intent);}
				}});
	        
	        listView.setMode(Mode.BOTH);
	        
	        registerForContextMenu(mListView);
	}
	class OnDetailClickListener implements OnCjjlDetailClickListener {
		@Override
		public void clickListener(int position) {
//			detail(position);
		}
	}
	private void detail(int position){
		positions = position;
		DzCpItem mDzCpItem = listData.get(position);
		app_uuid=mDzCpItem.getKey();
   		new AlertDialog.Builder(DzCpPosGeRenXxActivity.this).setTitle("系统提示").setMessage(app_uuid).setPositiveButton("确定", new DialogInterface.OnClickListener() {
			
			@Override
			public void onClick(DialogInterface dialog, int which) {
				// TODO Auto-generated method stub
				mDzCpKhXxPosPresenter.getDeleteDzcpPos(app_uuid);
			}
		}).setNegativeButton("返回", new DialogInterface.OnClickListener() {
			
			@Override
			public void onClick(DialogInterface dialog, int which) {
				// TODO Auto-generated method stub
				
			}
		}).show();
   		
   	}
	private void init() {
		listData.clear();
		mDzCpKhXxPosPresenter =new DzCpKhXxPosPresenter(this);
		SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); 
        String time = formatter.format(new  Date());
        TAppYh user = BankApplication.mInstance.getCurrentUser();
        String zjh=user.getSfz();
        JSONObject content  =new JSONObject();
        try {
        	content.put("offset", offset);
        	content.put("time", time);
        	content.put("zjh", zjh);
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
        mDzCpKhXxPosPresenter.getPosGeRenListData(content.toString());
		
		
	}
	@Override
	public void showProgressDialog(String msg) {
		// TODO Auto-generated method stub
		mProgressDialog.setMessage(msg);
		mProgressDialog.show();
	}
	@Override
	public void hideProgressDialog() {
		// TODO Auto-generated method stub
		mProgressDialog.hide();
	}
	@Override
	public void showMessage(String msg) {
		// TODO Auto-generated method stub
		BaseToast.getInstance().ShowSystemToast(this, msg);
	}
	@Override
	public void updateViewpos(int type, Object Obj) {
		// TODO Auto-generated method stub
		
	}
	@Override
	public void success() {
		// TODO Auto-generated method stub
		
	}
	@Override
	public void scsuccess() {
		// TODO Auto-generated method stub
		listData.remove(positions);
		listView.onRefreshComplete();
		mAdapter.notifyDataSetChanged();
		showMessage("刷新成功");
	}
	@Override
	public void updateListpos(List<DzCpkhXxDjPos> mList) {
		// TODO Auto-generated method stub
		dzcpkhxxposList = mList;
		for (DzCpkhXxDjPos mdzcpkhxxposlList : mList){
			DzCpItem mImageItem = new DzCpItem();
			mImageItem.setIdKey(mdzcpkhxxposlList.getId());
	        mImageItem.setKey(mdzcpkhxxposlList.getAppUuid());
	        mImageItem.setValue(mdzcpkhxxposlList.getKhMc());
	        mImageItem.setSfz(mdzcpkhxxposlList.getKhZjh());
	        mImageItem.setType(1);
	       int sbzt = mdzcpkhxxposlList.getSbZt();
    	   mImageItem.setLx(mdzcpkhxxposlList.getSbZtMc());
	        mImageItem.setImg("POS");
	       mImageItem.setZt(String.valueOf(mdzcpkhxxposlList.getSbZt()));
	        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); 
	        String dateString = formatter.format(mdzcpkhxxposlList.getSqSj());
	        mImageItem.setDate(dateString);
	        String [] str = dateString.split(" "); 
	        mImageItem.setXsSj(str[0]);
	        listData.add(mImageItem);
	}
		listView.onRefreshComplete();
		mAdapter.notifyDataSetChanged();
		
		showMessage("刷新成功");
}
	public void queryClick(View arg0){
		query();
	}
	
	private void query(){
		listData.clear();
		String val = edit_query.getText().toString();
	    JSONObject content  =new JSONObject();
	    TAppYh user = BankApplication.mInstance.getCurrentUser();
    	String zjh=user.getZh();
    	try {
    		content.put("zjh", zjh);
        	content.put("val", val);
        	content.put("strs", strs);
        	
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	    mDzCpKhXxPosPresenter.searchShaiXuanDzcpPos(content.toString());
		
		
	}
	@Override
	public void jyZhj(String arg0) {
		// TODO Auto-generated method stub
		
	}
	public void addClick(View arg0){
		 MyClickListener mMyClickListener= new MyClickListener();
		  config = new DialogConfigSpinner(this, getResources().getString(R.string.param198), true, mMyClickListener);
		  if(list.size()>0 && !strs.equals("")){
			  config.getLx(list);
		  }
		  config.show();
	}
	
	class  MyClickListener implements OnClickListener{

		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			int count = config.getCountCpZlXx();
			
			if(count==1){
			  shaixuan();
				
				
			}else if(count>1){
//				queryti();
				shaixuan();
			}else if(count ==0){
				strs="";
				config.dismiss();
				init();
			
			}
			
		}

private void shaixuan() {
			// TODO Auto-generated method stub
	config.dismiss();
//	 lx = config.getCpZlXx();
	String val = edit_query.getText().toString();
	list = config.getCpZlXx();
	 strs=list.toString();
	SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); 
	TAppYh user = BankApplication.mInstance.getCurrentUser();
    String zjh=user.getSfz();
    JSONObject content  =new JSONObject();
    try {
    	content.put("zjh", zjh);
    	content.put("val", val);
    	content.put("strs", strs);
    	
	} catch (JSONException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}
	mDzCpKhXxPosPresenter.searchShaiXuanDzcpPos(content.toString());
		}

private void queryti() {
			// TODO Auto-generated method stub
   new AlertDialog.Builder(DzCpPosGeRenXxActivity.this).setTitle("系统提示").setMessage(getResources().getString(R.string.param199)).setPositiveButton("确定", null).show();
		}
		 
	 }
	@Override
	public void refreshData(List<DzCpkhXxDjPos> mList) {
		// TODO Auto-generated method stub
		listData.clear();
		for (DzCpkhXxDjPos mdzcpkhxxposlList : mList){
			DzCpItem mImageItem = new DzCpItem();
			mImageItem.setIdKey(mdzcpkhxxposlList.getId());
	        mImageItem.setKey(mdzcpkhxxposlList.getAppUuid());
	        mImageItem.setValue(mdzcpkhxxposlList.getKhMc());
	        mImageItem.setSfz(mdzcpkhxxposlList.getKhZjh());
	        mImageItem.setType(1);
	       int sbzt = mdzcpkhxxposlList.getSbZt();
    	   mImageItem.setLx(mdzcpkhxxposlList.getSbZtMc());
	        mImageItem.setImg("POS");
	        mImageItem.setZt(String.valueOf(mdzcpkhxxposlList.getSbZt()));
	        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); 
	        String dateString = formatter.format(mdzcpkhxxposlList.getSqSj());
	        mImageItem.setDate(dateString);
	        String [] str = dateString.split(" "); 
	        mImageItem.setXsSj(str[0]);
	        listData.add(mImageItem);
	}
		listView.onRefreshComplete();
		mAdapter.notifyDataSetChanged();
		
		showMessage("刷新成功");
	}
}